package org.deltaset.meta.internal;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.deltaset.meta.CollectionHandler;

/**
 *
 * @author dmakariev
 */
class CollectionHandlerImpl implements CollectionHandler {

    public CollectionHandlerImpl() {
    }
    private static final Logger logger = Logger.getLogger(CollectionHandlerImpl.class.getName());

    @Override
    public void moveUp(final List list, final int currentIndex) {
        if (currentIndex > 0) {
            final int previousIndex = currentIndex - 1;
            Collections.swap(list, previousIndex, currentIndex);
        }
    }

    @Override
    public void moveDown(final List list, final int currentIndex) {
        if (currentIndex < list.size() - 1) {
            final int nextIndex = currentIndex + 1;
            Collections.swap(list, nextIndex, currentIndex);
        }
    }

    @Override
    public void moveTo(final List list, final int sourceIndex, final int targetIndex) {
        final int minIndex = 0;
        final int maxIndex = list.size() - 1;
        if (sourceIndex < minIndex || sourceIndex > maxIndex) {
            return;
        }
        final int realTargetIndex = (targetIndex < minIndex) ? minIndex : (targetIndex > maxIndex) ? maxIndex : targetIndex;
        final Object sourceElement = list.get(sourceIndex);
        list.remove(sourceIndex);
        list.add(realTargetIndex, sourceElement);
    }

    @Override
    public void removeElement(Collection collection, Object element) {
        final boolean removed = collection.remove(element);       
        logger.log(Level.INFO, " MetaCrudNamingContainer removeElement={0}  collection:{1}; element={2}", new Object[]{removed, collection, element});
    }

    @Override
    public List convertToList(Collection collection) {
        if (null == collection) {
            return Collections.emptyList();
        }
        if(collection instanceof List){
            return (List) collection;
        }
        final List result = new ArrayList();
        for (Object object : collection) {
            result.add(object);
        }
        return result;
    }
}
